package io.nanfeng.scope

import kotlin.reflect.KProperty

// 1
class SomeScope(var int: Int)

// 2
context(SomeScope)
class Node {
    // 3
    context(SomeScope)
    var reference: String
        get() {
            println("reference.get()@$int")
            return ""
        }
        set(value) {
            println("reference.set('$value')@$int")
        }

    // 4
    var testDelegate: Int by TransactionalVariable()

    //  5
    fun sayHello() {
        println("hello@$int")
    }
}

// 6
class TransactionalVariable {
    context(SomeScope)
            operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
        val int: Int = int
        return int
    }

    context(SomeScope)
            operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
        int = value
    }
}

//
//// Only available for get/set in a context of Transaction
//val userName by TransactionalVariable<String>()
fun main() {

//    7
    val node = with(SomeScope(1)) {
        Node().also { node ->
            node.reference
            node.reference = "u1"
        }
    }

//    8
    with(SomeScope(2)) {
        node.reference
        node.reference = "u2"
    }
//    9
//    No required context receiver found: SomeScope: Ctx { class Node }
//    val node2=Node()

}